Avatar

This article will dive into rendering multiple components at run time. Until now, we have not used external data in the projects. But to use external data, we first need to know about repeating elements.

We have already used repeating elements before when we iterated over a list of objects and rendered multiple components on screen.Since JSX is seen as plain JavaScript by the browser, we can use any JavaScript inside the template tags in JSX by enclosing it with curly braces ( { } ). An example is shown below:

This feature allows us to use the basic features of JavaScript inside our template tags, including iterators, such as map and forEach. For example, we can convert a value from a single integer to a list of integers, use a map inside our components, and return a list of React components.

But the lists are not uniquely identifiable because React uses the virtual DOM to attempt to limit the number of DOM elements that need to be updated when it rerenders the view. That is, if nothing has changed, React won't make the browser update anything to save on work, to improve React's performance. This feature is fantastic for building web applications, but sometimes we have to help React out by providing unique identifiers for nodes. Mapping over a list and rendering components in the map is one of those times.

React expects us to uniquely identify components by using a special prop: The key prop for each element of the list. The key prop can be anything we want, but it must be unique for that element. In our example, we can use the i variable in the map as no other element in the array has the same value. The updated code will look as follows.

We talked about building a parent-child relationship in earlier articles, but let's dive a bit more into detail about how we get access to the children inside a parent component and how we can render them.

On day-10, we had built a component to handle date formatting within the Clock component to give our users flexibility with their custom clock rendering. Recall that the implementation we created was relatively complex. We can use the React.Children object to map over a list of React objects, and React will do most of the work. The result of this is a much cleaner Formatter component:

The React.Children object provides some nice utility functions for dealing with children. Our Formatter example above uses the map function to iterate through the children and clone each one in the list. It creates a key (if necessary) for each one, freeing us from having to manage the uniqueness ourselves.

We have learnt about repeating elements in this article. In the next article, we're going to get into interacting with a server so we can use it in our React apps. The complete code for this article is available on my Github.

« Read Previous Article in this Series